package com.jackstraw.jack_base.datasource.redis.bean;

import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import org.springframework.boot.autoconfigure.data.redis.LettuceClientConfigurationBuilderCustomizer;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;

import java.time.Duration;

/**
 *
 */
public class MyLettuceClientConfigurationBuilderCustomizer implements LettuceClientConfigurationBuilderCustomizer {
    /**
     * Customize the {@link LettuceClientConfiguration.LettuceClientConfigurationBuilder}.
     *
     * @param clientConfigurationBuilder the builder to customize
     */
    @Override
    public void customize(
            LettuceClientConfiguration.LettuceClientConfigurationBuilder clientConfigurationBuilder) {
        /*
        ClusterTopologyRefreshOptions配置用于开启自适应刷新和定时刷新。如自适应刷新不开启，Redis集群变更时将会导致连接异常！
         */
        ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
                //开启自适应刷新
                .enableAdaptiveRefreshTrigger(ClusterTopologyRefreshOptions.RefreshTrigger.MOVED_REDIRECT,
                        ClusterTopologyRefreshOptions.RefreshTrigger.PERSISTENT_RECONNECTS)
                .enableAllAdaptiveRefreshTriggers()
                .adaptiveRefreshTriggersTimeout(Duration.ofSeconds(10))
                //开启定时刷新,时间间隔根据实际情况修改
                .enablePeriodicRefresh(Duration.ofSeconds(15))
                .build();

        clientConfigurationBuilder.clientOptions(
                ClusterClientOptions.builder().topologyRefreshOptions(topologyRefreshOptions).build());


    }
}
